<?php

namespace app\api\controller;

use app\api\model\Article as ArticleModel;
use app\api\model\Third;
use app\api\model\User as UserModel;
use app\api\model\Share;
use app\api\model\Video;
use app\common\controller\Api;
use think\Config;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login','GetPhone'];
    protected $noNeedRight = '*';

    public function login()
    {
        $code= $this->request->param('code');
        $appid = Config::get("site.appid");//小程序的appid
        $appSecret = Config::get("site.secret");// 小程序的$appSecret
        $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid，appsecret，code拼接到url里
        $result = self::curl_get($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
        if(empty($wxResult)){
            $this->error('错误');
        }else{
            if(!empty($wxResult['errcode'])){
                $this->error($wxResult['errmsg']);
            }
            $openid = $wxResult['openid'];
            $where_third['openid']=$openid;
            $Third = new Third();
            $UserModel = new UserModel();
            $Third_find= $Third->get($where_third);
            if(empty($Third_find)){
                $data_user['nickname']=Config::get("site.nickname");
                $data_user['avatar']=Config::get("site.avatar");
                $data_user['jointime']=time();
                $data_user['status']="normal";
                $UserModel->save($data_user);
                $Third->user_id=$UserModel->id;
                $Third->platform="微信";
                $Third->apptype="小程序";
                $Third->openid=$openid;
                $Third->save();
                $this->auth->direct($UserModel->id);
                $data['is_mobile']=0;
            }else{
                $this->auth->direct($Third_find['user_id']);
                $user_find=$UserModel->get($Third_find['user_id']);
                if(empty($user_find['mobile'])){
                    $is_mobile=0;
                }else{
                    $is_mobile=1;
                }
                $data['is_mobile']=$is_mobile;
            }
            $data['token']=$this->auth->getToken();
            $this->success('',$data);
        }
    }
    public function GetPhone()
    {
        $user= $this->auth;
        $UserModel = new UserModel();
        $code= $this->request->param('code');
        $appid = Config::get("site.appid");//小程序的appid
        $appSecret = Config::get("site.secret");// 小程序的$appSecret
        $wxUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid，appsecret，code拼接到url里
        $result = self::curl_get($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
        $GetPhoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$wxResult['access_token'];

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $GetPhoneUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{"code": "'.$code.'"}',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);

        $wxResultse = json_decode($response, true);
        if(empty($wxResultse)){
            $this->error('错误');
        }else{
            if($wxResultse['errcode']!=0){
                $this->error('获取失败,请重试');
            }else{
                $updata['mobile']=$wxResultse['phone_info']['phoneNumber'];
                $where['id']=$user->id;
                $UserModel->save($updata,$where);
                $this->success('');
            }
        }

    }

    /**
     * curl
     * @param $url
     * @param $httpCode
     * @return bool|string
     */
    public function curl_get($url, &$httpCode = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }

    public function info()
    {
        $user= $this->auth;
        $data['nickname']=$user->nickname;
        $data['avatar']=$user->avatar;
        $data['mobile']=$user->mobile;
        $this->success('',$data);
    }
    public function edit()
    {
        $user= $this->auth;
        $param = $this->request->param();
        $UserModel= new UserModel();
        $where['id']=$user->id;
        $UserModel->save($param,$where);
        $this->success('');
    }
    public function collect()
    {
        $type= $this->request->param('type');
        $user= $this->auth;
        $Share = new Share();
        $where['user_id']=$user->id;
        $where['status']=1;
        $where['type_data']=$type;
        $list=$Share->where($where)->order('id desc')->paginate()->each(function ($item, $key) {
            $Article = new ArticleModel();
            $Video = new Video();
            $where_find['id']=$item->num;
            if($item['type_data']==1){
                $find=$Article->where($where_find)->find();
            }else{
                $find=$Video->where($where_find)->find();
            }
            $item['title']=$find['title'];
            $item['cover_image']=$find['cover_image'];
            $item['abstract']=$find['abstract'];
            $item['view']=$find['view'];
            $item['createtime']=$find['createtime'];
            return $item;
        });
        $this->success('',$list);
    }
    public function forward()
    {
        $type= $this->request->param('type');
        $user= $this->auth;
        $Share = new Share();
        $where['user_id']=$user->id;
        $where['status']=2;
        $where['type_data']=$type;
        $list=$Share->where($where)->order('id desc')->paginate()->each(function ($item, $key) {
            $Article = new ArticleModel();
            $Video = new Video();
            $where_find['id']=$item->num;
            if($item['type_data']==1){
                $find=$Article->where($where_find)->find();
            }else{
                $find=$Video->where($where_find)->find();
            }
            $item['title']=$find['title'];
            $item['cover_image']=$find['cover_image'];
            $item['abstract']=$find['abstract'];
            $item['view']=$find['view'];
            $item['createtime']=$find['createtime'];
            return $item;
        });
        $this->success('',$list);
    }
}
